﻿using System.Configuration;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

namespace MsgQueueTest.Mail
{
    public class MailManager
    {
        public static void SendMail(string toAddress, string toName, string subject, string boby)
        {
            var appConfigHelper = new AppSettingsReader();
            var account = (string) appConfigHelper.GetValue("EmailAccout", typeof (string));
            var name = (string) appConfigHelper.GetValue("EmailName", typeof (string));
            var pass = (string) appConfigHelper.GetValue("EmailPass", typeof (string));

            ServicePointManager.ServerCertificateValidationCallback =
                new RemoteCertificateValidationCallback(TrustAllCertificateValidationCallback);

            var smtpClient = new SmtpClient("smtp.126.com")
                                 {
                                     Credentials = new NetworkCredential(account, pass)//,
                                     //Port = 587,
                                     //EnableSsl = true
                                 };


            var mailMessage = new MailMessage(new MailAddress(account, name),
                                              new MailAddress(toAddress, toName))
                                  {
                                      Subject = subject,
                                      Body = boby
                                  };

            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtpClient.Send(mailMessage);
        }

        private static bool TrustAllCertificateValidationCallback(object sender, X509Certificate certificate,
                                                                  X509Chain chain, SslPolicyErrors sslpolicyerrors)
        {
            return true;
        }
    }
}